<?php

namespace App\Services\TransferGoldBean;

use App\Models\User;
use App\Models\GoldBean;
use App\Http\Controllers\Api\V1\Requests\FormRequest;

class TransferGoldBeanRequest extends FormRequest
{
	protected $child;

	public function rules()
	{

		return [
			'child_id' => [
				$this->inviteCode(),
			],
			'amount' => [
				'required',
				'integer',
				$this->amount(),
			],
		];
	}

	public function inviteCode()
	{
		return function ($key, $value, $fail) {

			/**
			 * @var User $user
			 */
			$user = $this->user();
			$child = User::find($value);

			if (! $child) {
				return $fail('目标用户不存在');
			} elseif ($child->id == $user->id) {
				return $fail('仅可向他人转出');
			} elseif (empty($child->parent_id)) {
				return $fail('操作失败，仅可以上级为下级转出金豆');
			} elseif ($child->id < $child->parent->id) {
				return $fail('操作失败，仅可以上级为下级转出金豆');
			} elseif ($child->id < $user->id) {
				return $fail('操作失败，仅可以上级为下级转出金豆');
			} elseif ($child->parent_id == $user->parent_id) {
				return $fail('操作失败，仅可以上级为下级转出金豆');
			} else {
				$this->child = $child;
				return true;
			}
		};
	}

	public function amount()
	{
		return function ($key, $value, $fail) {
			if ($value <= 0) {
				return $fail("请输入正确的数量");
			} elseif ($this->isFloatInvalid($value)) {
                return $fail("请输入正确的数量");
            } elseif ($this->user()->gold_beans <= 50) {
				return $fail("金豆不足，低于{$this->allowedLowestTransferBeans()}颗不得转出");
			} elseif ($this->user()->gold_beans < $value) {
				return $fail("金豆不足，低于{$this->allowedLowestTransferBeans()}颗不得转出");
			} elseif (! $this->isLowestTransferBeansMatched()) {
				return $fail("金豆不足，低于{$this->allowedLowestTransferBeans()}颗不得转出");
			} else {
				return true;
			}
		};
	}

	protected function allowedLowestTransferBeans()
	{
		return GoldBean::allowedLowestTransferBeans();
	}

	protected function allowedTransferMultiple()
	{
		return GoldBean::allowedTransferMultiple();
	}

	protected function isLowestTransferBeansMatched()
	{
		return big_decimal($this->user()->gold_beans)->minus($this->allowedLowestTransferBeans())->isGreaterThanOrEqualTo($this->amount);
		//GoldBean::isLowestTransferBeansMatched($this->amount);
	}

	protected function isTransferMultipleMatched()
	{
		return GoldBean::isTransferMultipleMatched($this->amount);
	}

	public function getChild()
	{
		return $this->child;
	}
}
